<template>
  <div style="border: 1px solid snow">
    <!-- 文章属性设置表单部分 -->
    <div>
      <el-form :model="state.article" :rules="editBlogRules" ref="editBlogRulesRef">
        <el-row>
          <!-- 标题&简介 -->
          <el-col :span="14">
            <el-form-item size="large" label="文章名称" :label-width="formLabelWidth" class="editBlog-font" prop="title">
              <el-input v-model="state.article.title" auto-complete="off" placeholder="请输入文章标题" clearable></el-input>
            </el-form-item>
            <el-form-item size="large" label="文章简介" :label-width="formLabelWidth" class="editBlog-font" prop="summary">
              <el-input v-model="state.article.summary" auto-complete="off" placeholder="请输入文章简介" clearable></el-input>
            </el-form-item>
          </el-col>
          <!-- 文章封面 -->
          <el-col :span="8">
            <el-form-item label="标题图" :label-width="formLabelWidth" class="editBlog-font item-center">
              <el-col :span="2">
                <el-popover
                    placement="bottom"
                    :width="160"
                    v-model:visible="selectImgVisible"
                >
                  <p>随机获取一张图片</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="small" text @click="selectImgVisible = false">取消</el-button>
                    <el-button size="small" type="primary" @click="randomImg()">确定</el-button>
                  </div>
                  <template #reference>
                    <el-icon style="margin-top: 8px">
                      <Bell/>
                    </el-icon>
                  </template>
                </el-popover>
              </el-col>
              <el-col :span="2">
                <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :http-request="handleAvatarHttp"
                    :before-upload="beforeAvatarUpload"
                >
                  <img v-if="state.article.coverImage !== ''" :src="state.article.coverImage" class="avatar"  alt="封面"/>
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6.5">
            <el-form-item label="标签" :label-width="formLabelWidth" class="editBlog-font" prop="tags">
              <el-tag
                  v-for="tag in state.article.tags"
                  :key="tag"
                  size="large"
                  class="mx-1"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <div v-show="state.article.tags.length < 3">
<!--                <el-input-->
<!--                    v-if="tagInputVisible"-->
<!--                    ref="InputRef"-->
<!--                    v-model="tagValue"-->
<!--                    size="small"-->
<!--                    @keyup.enter="tagInputConfirm"-->
<!--                    @blur="tagInputConfirm"-->
<!--                    style="width:100px"-->
<!--                />-->
                <el-select
                    ref="InputRef"
                    size="default"
                    v-if="tagInputVisible"
                    v-model="tagValue"
                    filterable
                    placeholder="Select"
                    @keyup.enter="tagInputConfirm"
                    style="width:100px">
                  <el-option
                      v-for="item in allTag"
                      :value="item.name"
                  />
                </el-select>
                <el-button v-else class="button-new-tag" size="default" @click="showTagInput">
                  + 新标签
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="分类" :label-width="formLabelWidth" class="editBlog-font" prop="categoryId">
              <el-select v-model="state.article.categoryId" filterable placeholder="请选择分类">
                <el-option
                    v-for="item in allCategory"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="是否置顶" :label-width="formLabelWidth" class="editBlog-font" prop="isWeight">
              <div>
                <el-radio-group v-model="state.article.isWeight">
                  <el-radio :label="0" size="default" border>否</el-radio>
                  <el-radio :label="1" size="default" border>是</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="是否发布" :label-width="formLabelWidth" class="editBlog-font" prop="isPublish">
              <div>
                <el-radio-group v-model="state.article.isPublish">
                  <el-radio :label="0" size="default" border>下架</el-radio>
                  <el-radio :label="1" size="default" border>发布</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6.5">
            <el-form-item label="是否开启评论" :label-width="formLabelWidth" class="editBlog-font" prop="isComment">
              <div>
                <el-radio-group v-model="state.article.isComment">
                  <el-radio :label="0" size="default" border>关闭</el-radio>
                  <el-radio :label="1" size="default" border>开启</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="创作类型" :label-width="formLabelWidth" class="editBlog-font" prop="isOriginal">
              <div>
                <el-radio-group v-model="state.article.isOriginal">
                  <el-radio :label='0' size="default" border>原创</el-radio>
                  <el-radio :label='1' size="default" border>转载</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item v-if="state.article.isOriginal === 1 || state.article.isOriginal === '1'" label="原文链接" :label-width="formLabelWidth" class="editBlog-font" prop="originalLink">
              <el-input v-model="state.article.originalLink" placeholder="请输入链接" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <!--  撰写文档部分  -->
        <el-row>
          <el-col :span="24">
              <vue-markdown-editor
                v-model="state.article.content"
                height="600px"
                :disabled-menus="[]"
                @upload-image="handleUploadImage"
                @copy-code-success="handleCopyCodeSuccess"
                left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code emoji"
                >
              </vue-markdown-editor>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="10"></el-col>
          <el-col :span="4" class="editBlog-footer">
          <span >
              <el-button @click="router.push('/modules')">取 消</el-button>
              <el-button type="primary"  @click="blogConfirm(editBlogRulesRef)">确 定</el-button>
          </span>
          </el-col>
          <el-col :span="10"></el-col>

        </el-row>
      </el-form>
    </div>
  </div>

</template>

<script lang="ts" setup>

import {nextTick, onBeforeMount, onMounted, reactive, ref} from "vue";
import VueMarkdownEditor from '@kangc/v-md-editor'
import {Bell, Plus} from '@element-plus/icons-vue'
import {ElInput, ElMessage, ElNotification, FormInstance, FormRules, UploadFile, UploadFiles} from 'element-plus'
import type {UploadProps} from 'element-plus'
import {useRouter} from "vue-router";
import request from "../../utils/request.js";
import store from "../../store";

const router = useRouter();

// 所有数据
const state = reactive({
  article: {
    isPublish: 0,
    isWeight: 0,
    isOriginal: 0,
    isComment: 0,
    content: '',
    originalLink: '',
    categoryId: '',
    title: '',
    summary: '',
    tags: [],
    coverImage: ''
  }
})

// 校验
const editBlogRulesRef = ref<FormInstance>();
const editBlogRules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 100, message: '长度必须为5-50', trigger: 'blur' },
  ],
  summary: [
    { required: true, message: '请输入简介', trigger: 'blur' },
    { min: 10, max: 200, message: '长度必须为10-100', trigger: 'blur' },
  ],
  tags: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change',
    },
  ],
  categoryId: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
  isComment: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
  isWeight: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
  isPublish: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
  isOriginal: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
  originalLink: [
    {
      required: true,
      message: '必填字段',
      trigger: 'change'
    },
  ],
})

// 预设
const formLabelWidth = ref('120px')
const selectImgVisible = ref(false);
const allTag = ref([]);
const allCategory = ref([]);

// 标签
const tagValue = ref({})
const dynamicTags = ref(['Tag 1', 'Tag 2', 'Tag 3'])
const tagInputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 获取所有标签
const getAllTag = ()=>{
  request.get("/tag/getAllTag").then((res:any)=>{
    allTag.value = res.data;
  })
}

// 获取所有分类
const getAllCategory = ()=>{
  request.get("/category/getAllCategory").then((res:any)=>{
    allCategory.value = res.data;
  })
}

// 上传封面图片
const handleAvatarHttp: UploadProps['onSuccess'] = (uploadFile: any, uploadFiles: any) => {
  // console.log(uploadFile.file)
  // 配置
  let param = new FormData();
  param.append("image",uploadFile.file);
  let config = {headers: {"Content-Type": "multipart/form-data"}}
  let url = "/upload";

  // 发送请求
  request.post(url,param,config).then((res: any)=>{
    state.article.coverImage = res.data
  })
}

// 上传封面图片前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log("上传图片之前")
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小不得超过10MB！')
    return false
  }
  return true
}

// MarkDown 上传图片方法
const handleUploadImage = (event: any, insertImage: any, files: any) => {
  // 配置
  let param = new FormData();
  param.append("image",files[0]);
  let config = {headers: {"Content-Type": "multipart/form-data"}}
  let url = "/upload";

  // 发送请求
  request.post(url,param,config).then((res: any)=>{
    insertImage({
      url:res.data,
      desc: files[0].name
    })
  })
}

// MarkDown 点击复制按钮后
const handleCopyCodeSuccess = (code: any) => {
}

// 博客封面随机生成图片
const randomImg = () => {

}

// 关闭标签
const handleClose = (tag: string) => {
  state.article.tags.splice(dynamicTags.value.indexOf(tag), 1)
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
}

// 用户移除输入标签框或回车后的事件
const tagInputConfirm = () => {
  // 如果输入框有值的话，就添加到数组中
  if (tagValue.value && state.article.tags.indexOf(tagValue.value) === -1) {
    state.article.tags.push(tagValue.value)
    // 隐藏输入框
    tagInputVisible.value = false
    // 重置输入框
    tagValue.value = ''
  }

}

// 博客提交
const blogConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(!state.article.content){
        ElMessage.error("请编写文章内容！")
        return;
      }
      if(state.article.id != null && state.article.id != 0 && state.article.id != ''){
        request.put("/blog/edit",state.article).then((res:any)=>{
          if(res.code === 200){
            state.article = {
              isPublish: 1,
              isWeight: 1,
              isOriginal: 1,
              isComment: 1,
              content: '',
              originalLink: '',
              categoryId: '',
              title: '',
              summary: '',
              tags: [],
              coverImage: ''}
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            router.push("/modules")
          }
        })
      }else{
        request.post("/blog/add",state.article).then((res:any)=>{
          if(res.code === 200){
            state.article = {
              isPublish: 1,
              isWeight: 1,
              isOriginal: 1,
              isComment: 1,
              content: '',
              originalLink: '',
              categoryId: '',
              title: '',
              summary: '',
              tags: [],
              coverImage: ''}
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            router.push("/modules")
          }
        })
      }
    } else {

    }
  })
}

// 初始化数据
onMounted(()=>{
  getAllTag()
  getAllCategory()
  let blogId = store.getters.getEditBlogId;
  console.log(blogId)
  if(blogId && blogId != 0){
    request.get("/blog/getById/" + blogId).then((res:any)=>{
      state.article = res.data
      store.commit('removeEditBlogId')
    })
  }
})
</script>

<style scoped lang="scss">
.editBlog-footer{
  margin-top: 15px;
}

.mx-1{
  margin-right: 5px;
}

.editBlog-font :deep(.el-form-item__label){
  font-weight: bold !important;
}

.item-center :deep(.el-form-item__content) {
  align-items: start !important;
}

.avatar-uploader :deep(.avatar) {
  width: 200px;
  height: 110px;
  display: block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 200px;
  height: 110px;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 110px;
  text-align: center;
}
</style>

